package com.fjec.market.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fjec.common.enums.EnumSysCode;
import com.fjec.common.protocol.JsonResult;
import com.fjec.common.shiro.AccountInfo;
import com.fjec.common.util.DateUtil;
import com.fjec.common.util.JsonUtil;
import com.fjec.common.util.SequenceIdGenerator;
import com.fjec.market.entity.BizShoppingCart;
import com.fjec.market.entity.InfoSku;
import com.fjec.market.mapper.BizShoppingCartMapper;
import com.fjec.market.mapper.InfoSkuMapper;
import com.fjec.market.service.IBizShoppingCartService;
import com.fjec.market.view.ShoppingCartItemVO;
import org.apache.commons.collections.MapUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 016.购物车表 服务实现类
 * </p>
 *
 * @author admin
 * @since 2020-09-17
 */
@Service
public class BizShoppingCartServiceImpl extends ServiceImpl<BizShoppingCartMapper, BizShoppingCart> implements IBizShoppingCartService {

    @Resource
    private BizShoppingCartMapper mapper;

    @Resource
    private InfoSkuMapper infoSkuMapper;

    @Resource
    private SequenceIdGenerator idGenerator;

    @Resource(name = "phyOrderAmqpTemplate")
    private RabbitTemplate phyOrderAmqpTemplate;

    @Override
    public JsonResult save(Long skuId, Integer num) {
        // 获取商品SKU信息
        QueryWrapper<InfoSku> wrapper = new QueryWrapper<>();
        wrapper.eq("Id", skuId)
                .eq("delFlag", 0)
                .eq("saleable", 1)
                .eq("valid", 1);
        InfoSku sku = infoSkuMapper.selectOne(wrapper);
        // 校验商品是否已下架
        if (sku == null) {
            return JsonResult.failure()
                    .code(EnumSysCode.ERR_0040.getCode())
                    .message(EnumSysCode.ERR_0040.getMsg())
                    .build();
        }
        // 自己不能买自己的商品
        if (AccountInfo.isAuthenticated()) {
            Integer busiType = AccountInfo.getBusiType();
            Long busiId = AccountInfo.getBusiId();
            if (busiType != null && busiId != null
                    && sku.getBusiType().intValue() == busiType.intValue()
                    && sku.getBusiId().longValue() == busiId.longValue()) {
                return JsonResult.failure()
                        .code(EnumSysCode.ERR_3019.getCode())
                        .message(EnumSysCode.ERR_3019.getMsg())
                        .build();
            }
        }
        // 查询是否已入购物车
        QueryWrapper<BizShoppingCart> scQueryWrapper = new QueryWrapper<>();
        scQueryWrapper.eq("SkuId", skuId)
                .eq("UserId", AccountInfo.getUserId())
                .eq("DelFlag", 0);
        BizShoppingCart entity = mapper.selectOne(scQueryWrapper);
        if (entity == null) {
            // 保存入购物车
            entity = new BizShoppingCart();
            entity.setId(idGenerator.nextId());
            entity.setUserId(AccountInfo.getUserId());
            entity.setBusiType(sku.getBusiType());
            entity.setBusiId(sku.getBusiId());
            entity.setSkuId(skuId);
            entity.setSkuNum(num);
            entity.setDelFlag(0);
            entity.setCreateTime(DateUtil.nowLdt());
            entity.setRemark("");
            mapper.insert(entity);
        } else {
            // 增加数值
            entity.setSkuNum(entity.getSkuNum() + num);
            entity.setUpdateTime(DateUtil.nowLdt());
            mapper.updateById(entity);
        }
        return JsonResult.SUCCESS;
    }

    @Override
    public JsonResult getList() {
        List<Map<String, Object>> mapList = mapper.selectListByUserId(AccountInfo.getUserId());
        List<ShoppingCartItemVO> retList = new ArrayList<>();
        for (Map<String, Object> map : mapList) {
            ShoppingCartItemVO item = new ShoppingCartItemVO();
            item.setScId(MapUtils.getString(map, "scId"));
            item.setBusiId(MapUtils.getString(map, "BusiId"));
            item.setBusiType(MapUtils.getInteger(map, "BusiType"));
            item.setCompHeadPic(MapUtils.getString(map, "CompHeadPic"));
            item.setShopName(MapUtils.getString(map, "ShopName"));
            item.setSkuId(MapUtils.getString(map, "SkuId"));
            item.setNum(MapUtils.getInteger(map, "SkuNum"));
            item.setSkuTitle(MapUtils.getString(map, "SkuTitle"));
            item.setRetailPrice(MapUtils.getInteger(map, "RetailPrice"));
            item.setRetailSpec(MapUtils.getString(map, "RetailSpec"));
            String jsonStr = MapUtils.getString(map, "SpuPics");
            List<String> spuPics = JsonUtil.jsonToObject(jsonStr, List.class);
            item.setSpuPics(spuPics);
            retList.add(item);
        }
        return JsonResult.success()
                .data(retList)
                .build();
    }

    @Override
    public JsonResult changeNum(Long id, Integer num) {
        // 校验数量是否大于0
        if (num < 0) {
            return JsonResult.failure()
                    .code(EnumSysCode.ERR_0002.getCode())
                    .message(EnumSysCode.ERR_0002.getMsg())
                    .build();
        }
        // 获取购物车信息
        QueryWrapper<BizShoppingCart> scQueryWrapper = new QueryWrapper<>();
        scQueryWrapper.eq("id", id)
                .eq("delFlag", 0);
        BizShoppingCart entity = mapper.selectOne(scQueryWrapper);
        if (entity == null) {
            return JsonResult.failure()
                    .code(EnumSysCode.ERR_3008.getCode())
                    .message(EnumSysCode.ERR_3008.getMsg())
                    .build();
        }
        // 获取商品SKU信息
        QueryWrapper<InfoSku> skuQueryWrapper = new QueryWrapper<>();
        skuQueryWrapper.eq("Id", entity.getSkuId())
                .eq("delFlag", 0)
                .eq("saleable", 1)
                .eq("valid", 1);
        InfoSku sku = infoSkuMapper.selectOne(skuQueryWrapper);
        // 校验商品是否已下架
        if (sku == null) {
            return JsonResult.failure()
                    .code(EnumSysCode.ERR_0040.getCode())
                    .message(EnumSysCode.ERR_0040.getMsg())
                    .build();
        }
        entity.setSkuNum(num);
        entity.setUpdateTime(DateUtil.nowLdt());
        mapper.updateById(entity);
        entity = mapper.selectById(entity.getId());
        return JsonResult.success()
                .data(entity.getSkuNum())
                .build();
    }

    @Override
    public JsonResult delete(Long id) {
        // 获取购物车信息
        QueryWrapper<BizShoppingCart> scQueryWrapper = new QueryWrapper<>();
        scQueryWrapper.eq("id", id)
                .eq("delFlag", 0);
        BizShoppingCart entity = mapper.selectOne(scQueryWrapper);
        if (entity == null) {
            return JsonResult.failure()
                    .code(EnumSysCode.ERR_0040.getCode())
                    .message(EnumSysCode.ERR_0040.getMsg())
                    .build();
        }
        entity.setDelFlag(1);
        entity.setUpdateTime(DateUtil.nowLdt());
        mapper.updateById(entity);
        return JsonResult.success()
                .code(EnumSysCode.MSG_6004.getCode())
                .message(EnumSysCode.MSG_6004.getMsg())
                .build();
    }

}
